import { useContext, useEffect, useRef, useState } from 'react'
import SignaturePad from 'react-signature-canvas'

import { GlobalContext } from '@/context'
import locale from '@/pages/home/locale'
import useLocale from '@/utils/useLocale'

import styles from './styles/index.module.less'

const SignatureCanvas = ({
  value,
  onchange,
}: {
  value?: string
  onchange?: (base64: string) => void
}) => {
  const t = useLocale(locale)
  const canvasRef = useRef(null)
  const signatureRef = useRef(null)
  const { lang } = useContext(GlobalContext)
  const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 })

  const [base64, setBase64] = useState<string>(null)
  useEffect(() => {
    console.log('签字初始化值', value)
    setBase64(value)
    const resizeCanvas = () => {
      setCanvasSize({
        width: signatureRef.current.clientWidth,
        height: signatureRef.current.clientHeight,
      })
    }
    resizeCanvas()

    window.addEventListener('resize', resizeCanvas)
    return () => {
      window.removeEventListener('resize', resizeCanvas)
    }
  }, [])

  useEffect(() => {
    base64 && canvasRef.current.fromDataURL(base64, { ...canvasSize })
  }, [base64])

  const handleClear = () => {
    canvasRef.current.clear()
    onchange && onchange(null)
  }

  const handleSave = () => {
    if (canvasRef.current.isEmpty()) {
      console.log('签字清空')
      setBase64(null)
    }
    const data = canvasRef.current.toDataURL('image/png')
    console.log('签字变化', data)
    setBase64(data)
    onchange && onchange(data)
  }

  return (
    <div className={styles['signature']} ref={signatureRef}>
      <SignaturePad
        onEnd={handleSave}
        ref={canvasRef}
        canvasProps={{ ...canvasSize }}
        penColor="#000"
      />
      <div
        className={styles['signature-button']}
        style={lang === 'en-US' ? { right: '20px' } : { left: '20px' }}
      >
        {base64 ? (
          <span className={styles['signature-button-clear']} onClick={handleClear}>
            {t['form.details.signatures.clear']}
          </span>
        ) : (
          <></>
        )}
      </div>
    </div>
  )
}

export default SignatureCanvas

/**
 *   const [base64, setBase64] = useState<string>(null)
 *   <SignatureCanvas value={base64} onchange={(e) => setBase64(e)} />
 */
